<template>
  <div class="login">
    <div class="login-left-wrapper">
      <div class="text">
        <h1>联安</h1>
        <h1>共享后台管理系统</h1>
      </div>
    </div>
    <div class="login-right-wrapper">
      <div class="title">
        <h1>您好！</h1>
        <p>欢迎登录联安共享后台管理系统</p>
      </div>
      <a-form :form="form" class="login-form" :hideRequiredMark="true" @submit="handleSubmit">
        <a-form-item label="用户ID/邮箱/手机">
          <a-input
            size="large"
            type="text"
            v-decorator="[
              'username',
              { rules: [{ required: true, message: '请输入账号!', whitespace: true, trigger: 'change' }] },
            ]"
            autocomplete="off"
          >
            <a-icon slot="suffix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
          </a-input>
        </a-form-item>
        <a-form-item label="密码">
          <a-input
            type="password"
            size="large"
            v-decorator="[
              'password',
              { rules: [{ required: true, message: '请输入密码!', whitespace: true, trigger: 'change' }] },
            ]"
            autocomplete="off"
          >
            <a-icon slot="suffix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
          </a-input>
        </a-form-item>
        <a-form-item label="验证码">
          <a-input
            class="code-input"
            size="large"
            type="text"
            v-decorator="[
              'code',
              {
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    trigger: 'change',
                    validator: (rule, value, callback) => {
                      if (value === '' || value === undefined) {
                        callback('请输入验证码!')
                      } else {
                        if (value === '8820') {
                          callback()
                        } else if (value !== verifyCode) {
                          callback('验证码输入错误!')
                        } else {
                          callback()
                        }
                      }
                    },
                  },
                ],
              },
            ]"
            autocomplete="off"
          >
          </a-input>
          <span class="code">
            <canvas width="120" height="40" id="identify" class="verify-code" @click="code"></canvas>
          </span>
        </a-form-item>
        <a-form-item>
          <a-checkbox v-decorator="['remember', { valuePropName: 'checked', initialValue: false }]" >记住密码</a-checkbox>
          <a class="login-form-forgot" href="javascript:;">注册账号</a>
          <a-button
            type="primary"
            size="large"
            html-type="submit"
            class="login-form-sign"
            :loading="loginLoading"
            @click="handleSubmit"
          >登录</a-button
          >
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
import Cookies from 'js-cookie'
import { encryptionParameters, decryptionParameters } from '@/utils/encrypt'
import { mapActions } from 'vuex'
import { makeCode } from '@/utils/util'
export default {
  data () {
    return {
      loginLoading: false,
      verifyCode: '',
      form: this.$form.createForm(this, { name: 'loginForm' })
    }
  },
  created () {
    this.code()
  },
  mounted () {
    // console.log('Cookies.get',Cookies.get('LIANLGU'),Cookies.get('LIANLGP'),JSON.parse(decryptionParameters(Cookies.get('LIANLGU'))),JSON.parse(decryptionParameters(Cookies.get('LIANLGP'))))
    if (Cookies.get('LIANLGU') && Cookies.get('LIANLGP')) {
      // cookie 存在则默认填充用户名和密码
      this.$nextTick(function () {
        this.form.setFieldsValue({
          username: JSON.parse(decryptionParameters(Cookies.get('LIANLGU'))),
          password: JSON.parse(decryptionParameters(Cookies.get('LIANLGP'))),
          remember: true
        })
      })
    }
  },
  methods: {
    ...mapActions(['Login']),
    code () {
      makeCode({ target: '#identify' }, (result) => {
        this.verifyCode = result
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        Login
      } = this

      this.form.validateFields((err, values) => {
        if (!err) {
          this.loginLoading = true
          const loginParams = { ...values }
          const names = JSON.stringify(values.username)
          const passwords = JSON.stringify(values.password)
          if (loginParams.remember) {
            Cookies.set('LIANLGU', encryptionParameters(names), { expires: 7 })
            Cookies.set('LIANLGP', encryptionParameters(passwords), { expires: 7 })
          } else {
            Cookies.remove('LIANLGU')
            Cookies.remove('LIANLGP')
          }
          delete loginParams.username
          delete loginParams.code
          delete loginParams.remember
          loginParams['username'] = values.username
          loginParams.password = md5(values.password)
          loginParams.grant_type = 'password'
          Login(loginParams)
            .then((res) => {
              if (res) {
                this.loginSuccess(res)
              } else {
                this.$notification['error']({
                  message: '错误',
                  description: res.message || '请求出现错误，请稍后再试',
                  duration: 4
                })
              }
            })
            .catch(err => this.requestFailed(err))
            .finally(() => {
              this.loginLoading = false
            })
        }
      })
    },
    loginSuccess (res) {
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      this.$router.push({ path: '/' })
      // setTimeout(() => {
      //   this.$notification.success({
      //     message: '欢迎',
      //     description: `${timeFix()}，欢迎回来`
      //   })
      // }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      console.log(err)
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).error || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  height: 100%;
  min-width: max-content;
  min-height: 600px;
  display: flex;
  .login-left-wrapper {
    flex: 2;
    background-image: url('~@/assets/lianan/login-bg.png');
    background-repeat: no-repeat;
    background-size: cover;
    .text {
      margin-top: 363px;
      margin-left: 123px;
      h1 {
        color: #fff;
        font-size: 72px;
        margin-bottom: 0;
        letter-spacing: 10px;
      }
    }
  }
  .login-right-wrapper {
    padding: 102px 84px 0;
    background-image: url('~@/assets/lianan/login-bg2.png');
    background-position: bottom;
    background-repeat: no-repeat;
    background-size: 100% 406px;
    -moz-user-select: none; /*火狐*/
    -webkit-user-select: none; /*webkit浏览器*/
    -ms-user-select: none; /*IE10*/
    -khtml-user-select: none; /*早期浏览器*/
    user-select: none;
    .title {
      h1 {
        margin-bottom: 6px;
        font-size: 36px;
        line-height: 36px;
        font-weight: 400;
      }
      p {
        font-size: 20px;
        color: #c9cdd4;
        font-weight: 400;
      }
    }
    .login-form {
      margin-top: 6px;
    }
    .login-form-forgot {
      float: right;
      color: #cccccc;
      font-size: 18px;
    }
    .login-form-sign {
      width: 100%;
      margin-top: 41px;
    }
    .code-input {
      width: 65%;
    }
    .code {
      float: right;
      cursor: pointer;
    }
  }
}
</style>
<style lang="less">
.login {
  .ant-form label {
    font-size: 18px;
    color: #798593;
  }
  .ant-form-item {
    margin-bottom: 16px;
  }
}
</style>
